package com.alphasta.socketio;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.DataListener;
import com.alphasta.framework.aspectj.lang.annotation.Log;
import com.alphasta.framework.aspectj.lang.constant.BusinessType;
import com.alphasta.framework.aspectj.lang.constant.OperatorType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Order(1)
public class SocketIOServerRunner implements CommandLineRunner {

    private final SocketIOServer server;

    @Autowired
    public SocketIOServerRunner(SocketIOServer server) {
        this.server = server;
    }

    @Override
    public void run(String... args) throws Exception {
        server.addEventListener("update", Object.class, new DataListener<Object>() {
            @Override
            public void onData(SocketIOClient client, Object data, AckRequest ackRequest) {

                System.out.println("服务端接收到了数据:" + data);
                // broadcast messages to all clients
                server.getBroadcastOperations().sendEvent("onUpdate", "update");
                System.out.println("服务端已经向客户端广播:" + "onUpdate");
            }
        });
        server.start();
        Thread.sleep(Integer.MAX_VALUE);
        server.stop();
    }

    /**
     * 通过Socket连接打开远程终端的设备
     */
    @Log(title = "通过Socket连接打开远程终端的设备", action = BusinessType.UPDATE, channel = OperatorType.MOBILE)
    public boolean openLock(String socketUUID, int groupId, int doorIndex) {
        try {
            server.getClient(UUID.fromString(socketUUID)).sendEvent("openLock", groupId, doorIndex);
            return true;
        } catch (Exception e) {
            return false;
        }

        //server.getBroadcastOperations().sendEvent("openLock","1,1");
    }

	public boolean kdgCq(String deviceId) {
		// TODO 自动生成的方法存根
		 try {
	           // server.getClient(UUID.randomUUID()).sendEvent(deviceId);
	            server.getBroadcastOperations().sendEvent(deviceId);
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	}

	public boolean kdgOpenBybh(String deviceId, String fz, String bh) {
		// TODO 自动生成的方法存根
		 try {
	           // server.getClient(UUID.randomUUID()).sendEvent(deviceId);
	            server.getBroadcastOperations().sendEvent("openlock"+deviceId,fz,bh);
	            return true;
	        } catch (Exception e) {
	            return false;
	        }
	}
}

